package lib

import (
	"bufio"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"os"
	"path"
	"time"

	"github.com/tebeka/selenium"
)

var driver selenium.WebDriver

func GetBaiduImage(msg string) (imgURL string, err error) {
	url := fmt.Sprintf("https://image.baidu.com/search/index?tn=baiduimage&word=%s", msg)
	// new remote driver
	caps := selenium.Capabilities{"browserName": "chrome"}
	driver, err = selenium.NewRemote(caps, "http://127.0.0.1:4444/wd/hub")
	defer driver.Quit()
	if nil != err {
		return
	}
	err = driver.Get(url)
	if err != nil {
		return
	}
	ele, err := driver.FindElement(selenium.ByID, "imgid")
	if err != nil {
		return
	}
	aElement, err := ele.FindElements(selenium.ByTagName, "img")
	if err != nil {
		return
	}
	var data []string
	for _, v := range aElement {
		hrefs, err := v.GetAttribute("data-imgurl")
		if err != nil {
			continue
		}
		data = append(data, hrefs)
	}
	if len(data) > 0 {
		imgURL = data[rand.Intn(len(data)-1)]
	}
	return
}

func DownloadImage(url string) (filename string, err error) {
	resp, err := HttpGet(url)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	imgPath := fmt.Sprintf("%s%s/", "./public/", time.Now().Format("20060102"))
	IsExist, err := PathExists(imgPath)
	if !IsExist {
		err = os.Mkdir(imgPath, os.ModePerm)
		if err != nil {
			return
		}
	}
	// 根据图片url获取其文件名
	name := fmt.Sprintf("%s%s", time.Now().Format("150405"), path.Base(url))

	reader := bufio.NewReaderSize(resp.Body, 0)
	file, err := os.Create(imgPath + name)
	if err != nil {
		return
	}
	defer file.Close()
	// 获得文件的writer对象
	writer := bufio.NewWriter(file)
	_, err = io.Copy(writer, reader)
	if err != nil {
		return
	}
	writer.Flush()
	filename = imgPath + name
	return
}

func HttpGetMeizi(url string) (resp *http.Response, err error) {
	client := &http.Client{}
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return
	}
	req.Header.Add("User-Agent", getAgent())
	req.Header.Add("Referer", "https://www.mzitu.com/")
	resp, err = client.Do(req)
	return
}

func DownloadImageByMeizi(url string) (filename string, err error) {
	resp, err := HttpGetMeizi(url)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	imgPath := fmt.Sprintf("%s%s/", "./public/meizi/", time.Now().Format("20060102"))
	IsExist, err := PathExists(imgPath)
	if !IsExist {
		err = os.Mkdir(imgPath, os.ModePerm)
		if err != nil {
			return
		}
	}
	// 根据图片url获取其文件名
	name := fmt.Sprintf("%s%s", time.Now().Format("150405"), path.Base(url))

	reader := bufio.NewReaderSize(resp.Body, 0)
	file, err := os.Create(imgPath + name)
	if err != nil {
		return
	}
	defer file.Close()
	// 获得文件的writer对象
	writer := bufio.NewWriter(file)
	_, err = io.Copy(writer, reader)
	if err != nil {
		return
	}
	writer.Flush()
	filename = imgPath + name
	return
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
